//
//  HFDaysMenuView.m
//  HFCalendar
//
//  Created by Luffy on 2021/8/24.
//

#import "HFDaysMenuView.h"
#import "HFCalendarCollectionReusableView.h"
#import "HFCalendarCollectionViewCell.h"

#import "HFCalendarModel.h"

#import "HFCalendarHelper.h"
#import "HFCalendarHeader.h"

#define dayView_width  ((SCREEN_WIDTH - 3) / 7.f)
#define dayView_Height 40

@interface HFDaysMenuView () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, copy) NSArray <HFCalendarModel *>*collectionViewArr;

/// 记录点击Cell数组
@property (nonatomic, strong) NSMutableArray <NSIndexPath *>*selectedMutArr;
/// 数据模型
@property (nonatomic, strong) HFCalendarModel *model;

@property (nonatomic, strong) HFCalendarHelper *helper;


@end

@implementation HFDaysMenuView {
    NSString *_startDateString;
    NSString *_endDateString;
}

- (instancetype)initWithFrame:(CGRect)frame
              startDateString:(NSString *)startDateString
                endDateString:(NSString *)endDateString {
    self = [super initWithFrame:frame];
    if (self) {
        self.helper = [HFCalendarHelper defaultManager];
        self.model = [HFCalendarModel new];
        self.selectedMutArr = [@[] mutableCopy];
        
        // 数据源
        NSDateFormatter *formatter = [self.helper yearMonthAndDayFormatter];
        NSDate *startDate = [formatter dateFromString:startDateString];
        NSDate *endDate = [formatter dateFromString:endDateString];
        self.collectionViewArr = [self.model achieveModelWithData:startDate toDate:endDate];

        [self setupUI];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:(self.collectionViewArr.lastObject.numberOfDaysOfTheMonth + self.collectionViewArr.lastObject.firstDayOfTheMonth - 2) inSection:self.collectionViewArr.count - 1] animated:NO scrollPosition:UICollectionViewScrollPositionBottom];
}

#pragma mark - Delegate && DataSource (UI代理与数据源)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.collectionViewArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collectionViewArr[section].sectionRow * 7;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HFCalendarCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HFCalendarCollectionReusableView.description forIndexPath:indexPath];
        headerView.titleStr = self.collectionViewArr[indexPath.section].headerTitle;
        return headerView;
    }
    return [[UICollectionReusableView alloc] init];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HFCalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HFCalendarCollectionViewCell.description forIndexPath:indexPath];
    [cell layoutCellIndexPath:indexPath
                        model:self.collectionViewArr[indexPath.section]];
    
    // 中间元素颜色
    if (self.selectedMutArr.count == 2
        && [indexPath compare:self.selectedMutArr.firstObject] == NSOrderedDescending
        && [indexPath compare:self.selectedMutArr.lastObject] == NSOrderedAscending) {
        [cell changeContentViewBackgroundColor:CustomSelectContentColor];
        [cell changeDayTextColor:UIColor.whiteColor];
    }
    
    // 边界颜色
    [self.selectedMutArr enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.section == indexPath.section && obj.item == indexPath.item) {
            [cell changeContentViewBackgroundColor:CustomSelectBindaryColor];
            [cell changeDayTextColor:UIColor.whiteColor];
        }
    }];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    switch (self.selectedMutArr.count) {
        case 0:
        {
            [self setSelectFirstDateWithIndexPath:indexPath];
        }
            break;
        case 1:
        {
            [self setSelectSecondDateWithIndexPath:indexPath];
        }
            break;
        case 2:
        {
            [self reSelectWithIndexPath:indexPath];
        }
            break;
        default:
            break;
    }
}

#pragma mark - private Methods
// 选择第一个时间
- (void)setSelectFirstDateWithIndexPath:(NSIndexPath *)indexPath {
    [self changeTheSelectedCellStyleWithIndexPath:indexPath];
    
    [self.selectedMutArr addObject:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]];
    
    if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
        NSString *startString = [NSString stringWithFormat:@"%@%02ld日",self.collectionViewArr[indexPath.section].headerTitle,(long)(indexPath.item - (self.collectionViewArr[indexPath.section].firstDayOfTheMonth - 2))];
        [_delegate clickCalendarWithStartDate:startString andEndDate:nil];
    }
}

// 改变的样式为选中
- (void)changeTheSelectedCellStyleWithIndexPath:(NSIndexPath *)indexPath {
    HFCalendarCollectionViewCell *cell = (HFCalendarCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    [cell changeContentViewBackgroundColor:CustomSelectBindaryColor];
    [cell changeDayTextColor:UIColor.whiteColor];
}

// 选择第二个时间
- (void)setSelectSecondDateWithIndexPath:(NSIndexPath *)indexPath {
    // 如果第二次的选择和第一次的选择一样，则表示取消选择
    if ([self cancleCalendarSelectedWithIndexPath:indexPath]) {
        return;
    }
    
    NSString *startDate = [NSString stringWithFormat:@"%@%02ld日",self.collectionViewArr[self.selectedMutArr.firstObject.section].headerTitle,(long)(self.selectedMutArr.firstObject.item - (self.collectionViewArr[self.selectedMutArr.firstObject.section].firstDayOfTheMonth - 2))];
    NSString *endDate = [NSString stringWithFormat:@"%@%02ld日",self.collectionViewArr[indexPath.section].headerTitle,(long)(indexPath.item - (self.collectionViewArr[indexPath.section].firstDayOfTheMonth - 2))];
    
    NSDateComponents *components = [self.helper.calendar components:NSCalendarUnitDay fromDate:[self.helper.yearMonthAndDayFormatter dateFromString:startDate] toDate:[self.helper.yearMonthAndDayFormatter dateFromString:endDate] options:0];
    
    // 当设置了maxChooseNumber时，判断选择的时间段是否超出范围
    if (self.maxChooseNumber) {
        if (labs(components.day) > self.maxChooseNumber - 1) {
            if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
                [_delegate clickCalendarWithStartDate:startDate andEndDate:@"error"];
            }
            return;
        }
    }
    
    [self.selectedMutArr addObject:[NSIndexPath indexPathForRow:indexPath.item inSection:indexPath.section]];
    if ([self.selectedMutArr.firstObject compare:self.selectedMutArr.lastObject] == NSOrderedDescending) {
        self.selectedMutArr = [[[[self.selectedMutArr copy] reverseObjectEnumerator] allObjects] mutableCopy];
    }
    
    // 排序之后重新确定开始和结束时间
    startDate = [NSString stringWithFormat:@"%@%02ld日",self.collectionViewArr[self.selectedMutArr.firstObject.section].headerTitle,(long)(self.selectedMutArr.firstObject.item - (self.collectionViewArr[self.selectedMutArr.firstObject.section].firstDayOfTheMonth - 2))];
    endDate = [NSString stringWithFormat:@"%@%02ld日",self.collectionViewArr[self.selectedMutArr.lastObject.section].headerTitle,(long)(self.selectedMutArr.lastObject.item - (self.collectionViewArr[self.selectedMutArr.lastObject.section].firstDayOfTheMonth - 2))];
    
    if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
        [_delegate clickCalendarWithStartDate:startDate andEndDate:endDate];
    }
    
    [self.collectionView reloadData];
}

// 恢复成为未选中状态
- (void)recoveryIsNotSelectedWithIndexPath:(NSIndexPath *)indexPath {
    HFCalendarCollectionViewCell *cell = (HFCalendarCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    [cell changeContentViewBackgroundColor:UIColor.whiteColor];
    
    if ([self.helper whetherForTodayWithIndexPath:indexPath model:self.collectionViewArr[indexPath.section]] == HFDateEqualToToday) {
        [cell changeDayTextColor:CustomTodayColor];
    } else if (indexPath.item % 7 == 0 || indexPath.item % 7 == 6) {
        [cell changeDayTextColor:CustomRedColor];
    } else {
        [cell changeDayTextColor:CustomBlackColor];
    }
}

// 重新选择
- (void)reSelectWithIndexPath:(NSIndexPath *)indexPath {
    // 重新选择时，将之前点击的cell恢复成为点击状态，并移除数组中所有对象
    [self.selectedMutArr removeAllObjects];
    // 记录当前点击的Cell
    [self.selectedMutArr addObject:indexPath];

    if (_delegate && [_delegate respondsToSelector:@selector(clickCalendarWithStartDate:andEndDate:)]) {
        NSString *startString = [NSString stringWithFormat:@"%@%02ld日",self.collectionViewArr[indexPath.section].headerTitle,(long)(indexPath.item - (self.collectionViewArr[indexPath.section].firstDayOfTheMonth - 2))];
        [_delegate clickCalendarWithStartDate:startString andEndDate:nil];
    }
    
    [self.collectionView reloadData];
}

// 取消选择
- (BOOL)cancleCalendarSelectedWithIndexPath:(NSIndexPath *)indexPath {
    BOOL isCancleSelected = NO;
    
    if (self.selectedMutArr.firstObject.section == indexPath.section && self.selectedMutArr.firstObject.item == indexPath.item) {
        [self recoveryIsNotSelectedWithIndexPath:self.selectedMutArr.firstObject];
        [self.selectedMutArr removeAllObjects];

        if (_delegate && [_delegate respondsToSelector:@selector(clearCalendarDate)]) {
            [_delegate clearCalendarDate];
        }
        isCancleSelected = YES;
    }
    
    return isCancleSelected;
}

#pragma mark - Intial Methods
- (void)setupUI {
    self.backgroundColor = UIColor.whiteColor;
    
    [self addSubview:self.collectionView];
}

#pragma mark - Setter Getter Methods
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(dayView_width, dayView_Height);
        layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 50);
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        layout.minimumLineSpacing = 6;
        layout.minimumInteritemSpacing = 0.5;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerClass:HFCalendarCollectionReusableView.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HFCalendarCollectionReusableView.description];
        [_collectionView registerClass:HFCalendarCollectionViewCell.class forCellWithReuseIdentifier:HFCalendarCollectionViewCell.description];
    };
    return _collectionView;
}

- (void)setDateArray:(NSArray *)dateArray {
    _dateArray = dateArray;
    
    if (!_dateArray) {
        return;
    }
    // 传入两个时间时，查找其indexPath信息，用在collectionView上展现
    [self.collectionViewArr enumerateObjectsUsingBlock:^(HFCalendarModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.headerTitle isEqualToString:[_dateArray.firstObject substringWithRange:NSMakeRange(0, 8)]]) {
            NSInteger day = [_dateArray.firstObject substringWithRange:NSMakeRange(8, 2)].integerValue;
            [self.selectedMutArr addObject:[NSIndexPath indexPathForItem:(day + obj.firstDayOfTheMonth - 2) inSection:idx]];
        }
        
        if ([obj.headerTitle isEqualToString:[_dateArray.lastObject substringWithRange:NSMakeRange(0, 8)]]) {
            NSInteger day = [_dateArray.lastObject substringWithRange:NSMakeRange(8, 2)].integerValue;
            [self.selectedMutArr addObject:[NSIndexPath indexPathForItem:(day + obj.firstDayOfTheMonth - 2) inSection:idx]];
            [_collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:(self.collectionViewArr[idx].sectionRow * 7 - 1) inSection:idx] animated:NO scrollPosition:UICollectionViewScrollPositionBottom];
        }
    }];
    
    [_collectionView reloadData];
}

@end
